package com.ht.api.call.func.impl.ad;

import javax.sql.DataSource;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.DbList;
import com.ht.api.db.Entity;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 获取广告下的所有创意列表
 * @author asq
 * @createTime 2025年3月1日 14:01:20
 */
@Slf4j
public class GetCreativeInfoListFunctionCall implements IFunctionCall {

	@Override
	public String getName() {
		return "获取广告下的所有创意列表";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		// 获取登陆用户的数据源
		DataSource ds = me.getDataSource();
		
		// 获取广告ID
        String adId = param.getStr("ad_id");

        Entity ad = Db.createSqlParser("ad").findById(ds, adId);

        // 获取广告下的所有创意列表
        DbList creativeList = Db.createSqlParser("creative").where("ad_id", adId)
        		.order("order_num", "asc").order("sys_time", "asc").query(ds);

        int adType = ad.getInt("ad_type");
        for (Entity creative : creativeList) {

            if (adType == 1 || adType == 2) {
                JSONArray materials = creative.getJSONArray("material");

                if (materials != null) {
                    for (int i = 0; i < materials.size(); i++) {
                        JSONObject material = materials.getJSONObject(i);

                        if (material.getStr("type").equals("link")) {
                            String linkId = material.getStr("link_id");

                            Entity link = Db.createSqlParser("short_link").where("main_id", linkId).findOne(ds);
                            String relationId = link.getStr("relation_id");
                            String relationTable = link.getStr("relation_type");

                            Entity relation = Db.createSqlParser(relationTable).where("main_id", relationId).findOne(ds);

                            switch (relationTable) {
                                case "writings":
                                    material.set("title", relation.get("title"));
                                    material.set("cover", relation.get("cover_image"));
                                    material.set("desc", relation.get("desc_text"));
                                    break;
                            }

                        }
                    }
                }
                creative.set("material", materials);
            }



        }
        
		return JSONUtil.createObj().set("list", creativeList);
	}
}
